package com.shxc.smarttrade.old.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.RealTimeQuoteDatas;
import com.shxc.smarttrade.old.bean.TraderOrder;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.iview.IViewRealTimeQuote;
import com.shxc.smarttrade.old.myview.CommonAutoLinearLayout;
import com.shxc.smarttrade.old.presenter.MainPresenter;
import com.shxc.smarttrade.old.utils.Arith;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.CloseAllActivity;
import com.shxc.smarttrade.old.utils.CountClass;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/6/1.
 */

public class ChangeStopLossOrProfitActivity extends BaseActivity implements IViewRealTimeQuote {

    @BindView(R.id.tv_open_price)
    TextView tvOpenPrice;
    @BindView(R.id.tv_real_time_price)
    TextView tvRealTimePrice;
    @BindView(R.id.tv_stop_loss_range)
    TextView tvStopLossRange;
    @BindView(R.id.tv_stop_profit_range)
    TextView tvStopProfitRange;
    @BindView(R.id.tv_stop_loss)
    EditText tvStopLoss;
    @BindView(R.id.tv_loss)
    TextView tvLoss;
    @BindView(R.id.tv_stop_profit)
    EditText tvStopProfit;
    @BindView(R.id.tv_profit)
    TextView tvProfit;
    @BindView(R.id.iv_stop_loss_sub)
    ImageView ivStopLossSub;
    @BindView(R.id.iv_stop_loss_add)
    ImageView ivStopLossAdd;
    @BindView(R.id.iv_stop_profit_sub)
    ImageView ivStopProfitSub;
    @BindView(R.id.iv_stop_profit_add)
    ImageView ivStopProfitAdd;

    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.ll_all)
    CommonAutoLinearLayout llAll;

    MainPresenter presenter = new MainPresenter(this);
    private TraderOrder traderOrder;
    private double stopsLevel;//止盈止损远离步长
    private double stepSize;//止盈或止损每次加减的变化量
    private double mStopProfit;//记录实时止盈的最值
    private double mStopLoss;//记录实时止损的最值

    private double sl;//止损值
    private double tp;//值盈值
    private double stopLossTotal;//止损处总的改变量
    private double stopProfitTotal;//止盈处总的改变量
    private int cmd;//买涨还是买跌
    private double ask;//实时ask
    private double bid;//实时bid
    private double askTwo;//特殊ask
    private double bidTwo;//特殊bid
    private double openPrice;//开仓价
    private int contracSize;//
    private double volume;
    private boolean profitChange;
    private boolean profitUSDPrex;
    private int digits = -1;
    private int firstIn = 0;//标记是否首次获取实时数据


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_stoploss_or_profit);
        CloseAllActivity.getScreenManager().pushActivity(this);
        initView();
        initData();
        initListener();

    }

    /**
     * 初始化view
     */
    private void initView() {
        tvCenter.setText("设置止盈/止损");
    }

    private void initListener() {
        tvStopLoss.addTextChangedListener(new EditTextListener(0));
        tvStopProfit.addTextChangedListener(new EditTextListener(1));
        llAll.setOnSoftKeybordStatusListener(new CommonAutoLinearLayout.softKeybordStatusListener() {
            @Override
            public void softKeybordStatus(boolean status) {
                if (status) {
                    tvStopLoss.setCursorVisible(true);
                    tvStopProfit.setCursorVisible(true);
                } else {
                    tvStopLoss.setCursorVisible(false);
                    tvStopProfit.setCursorVisible(false);
                }
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initData() {
        /*double closePrice, double openPrice, int cmd, double ask, double bid,
                                   int contracSize, double volume, boolean profitChange, boolean profitUSDPrex*/
        Intent intent = getIntent();
        traderOrder = (TraderOrder) intent.getSerializableExtra("traderOrder");
        digits = traderOrder.getDigits();
        double multipy = traderOrder.getMultiply();
        stopsLevel = Arith.div(traderOrder.getStopsLevel(), multipy, (int) Math.log10(multipy));
        stepSize = Arith.div(1, multipy, (int) Math.log10(multipy));
        cmd = traderOrder.getCmd();
        openPrice = traderOrder.getOpenPrice();
        contracSize = traderOrder.getContractSize();
        volume = traderOrder.getVolume();
        profitChange = traderOrder.isProfitChange();
        profitUSDPrex = traderOrder.isProfitUSDPrex();
        ask = traderOrder.getAsk();
        bid = traderOrder.getBid();
        if (traderOrder.getTp() != 0) {
            tvStopProfit.setText(BaseUtils.getDigitsData(traderOrder.getTp(), digits));
        }
        if (traderOrder.getSl() != 0) {
            tvStopLoss.setText(BaseUtils.getDigitsData(traderOrder.getSl(), digits));
        }
        tvOpenPrice.setText(BaseUtils.getDigitsData(openPrice, digits));

        presenter.startRealTimeQuote(traderOrder.getSymbolEn() + "," + traderOrder.getProfitCalCurrency());
    }


    @OnClick(R.id.rl_left)
    public void rlLeft() {
        finish();
    }

    @OnClick({R.id.iv_stop_loss_sub, R.id.iv_stop_loss_add, R.id.iv_stop_profit_sub, R.id.iv_stop_profit_add})
    public void setSLOrTpViewClick(View view) {
        switch (view.getId()) {
            case R.id.iv_stop_loss_sub:
                setMySL(0);
                break;
            case R.id.iv_stop_loss_add:
                setMySL(1);
                break;
            case R.id.iv_stop_profit_sub:
                setMyTP(0);
                break;
            case R.id.iv_stop_profit_add:
                setMyTP(1);
                break;
        }
    }

    /**
     * 设置止损
     *
     * @param tagSL
     */
    private void setMySL(int tagSL) {
        if (tagSL == 0)
            stopLossTotal = Arith.sub(stopLossTotal, stepSize);
        else
            stopLossTotal = Arith.add(stopLossTotal, stepSize);

        double slcal = Arith.add(mStopLoss, stopLossTotal);
        tvStopLoss.setText(BaseUtils.getDigitsData(slcal, digits));
        if (cmd == 0) {//买涨
            if (slcal <= mStopLoss && slcal > 0) {
                sl = slcal;
                double profit;
                profit = getMyProfit(sl);
                if (profit == -1) return;
                tvLoss.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
            } else {
                tvLoss.setText("止损不在范围内");
                sl = 0;
            }
        } else {//买跌
            if (slcal >= mStopLoss) {
                sl = slcal;
                double profit;
                profit = getMyProfit(sl);
                if (profit == -1) return;
                tvLoss.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
            } else {
                tvLoss.setText("止损不在范围内");
                sl = 0;
            }

        }
    }

    /**
     * 设置止盈
     *
     * @param tagTP
     */
    private void setMyTP(int tagTP) {
        if (tagTP == 0)
            stopProfitTotal = Arith.sub(stopProfitTotal, stepSize);
        else
            stopProfitTotal = Arith.add(stopProfitTotal, stepSize);

        double tpcal = Arith.add(mStopProfit, stopProfitTotal);
        tvStopProfit.setText(BaseUtils.getDigitsData(tpcal, digits));
        if (cmd == 0) {
            if (tpcal >= mStopProfit) {
                tp = tpcal;
                double profit;
                profit = getMyProfit(tp);
                if (profit == -1) return;
                tvProfit.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
            } else {
                tvProfit.setText("止盈不在范围内");
                tp = 0;
            }
        } else {
            if (tpcal <= mStopProfit && tpcal > 0) {
                tp = tpcal;
                double profit;
                profit = getMyProfit(tp);
                if (profit == -1) return;
                tvProfit.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
            } else {
                tvProfit.setText("止盈不在范围内");
                tp = 0;
            }
        }
    }

    private double getMyProfit(double slOrTp) {
        return CountClass.getProfit(slOrTp, openPrice, cmd, askTwo, bidTwo, contracSize, volume, profitChange, profitUSDPrex);
    }

    /**
     * 确认修改
     */
    @OnClick(R.id.btn_change)
    public void btnChange() {
        if (tp == 0 && sl == 0)
            showToast("请先设置止盈/止损");
        else {
            showShortDialog();
            traderUpdata(traderOrder.getTicket(), SpUtils.getInt(getApplicationContext(), "userId"), tp, sl);
        }

    }

    @Override
    public void showDialog() {

    }

    @Override
    public void dismissDialog() {

    }

    /**
     * 接收实时报价
     *
     * @param quoteBeen
     */
    @Override
    public void setData(List<RealTimeQuoteDatas.DataBean.QuoteBean> quoteBeen) {
        RealTimeQuoteDatas.DataBean.QuoteBean qb = quoteBeen.get(0);
        ask = qb.getAsk();
        bid = qb.getBid();
        double[] askBidOne = new double[]{ask, bid};
        if (quoteBeen.size() > 1) {
            askTwo = quoteBeen.get(1).getAsk();
            bidTwo = quoteBeen.get(1).getBid();
        }
        double market = qb.getMarket();
        tvRealTimePrice.setText(BaseUtils.getDigitsData(market, digits));
        if (traderOrder.getCmd() == 0) {//买涨
            mStopProfit = Arith.add(bid, stopsLevel);
            mStopLoss = Arith.sub(bid, stopsLevel);
            tvStopLossRange.setText("≤ " + BaseUtils.getDigitsData(mStopLoss, digits));
            tvStopProfitRange.setText("≥ " + BaseUtils.getDigitsData(mStopProfit, digits));
        } else {//买跌
            mStopProfit = Arith.sub(ask, stopsLevel);
            mStopLoss = Arith.add(ask, stopsLevel);
            tvStopLossRange.setText("≥ " + BaseUtils.getDigitsData(mStopLoss, digits));
            tvStopProfitRange.setText("≤ " + BaseUtils.getDigitsData(mStopProfit, digits));
        }

        if (firstIn == 0) {
            if (traderOrder.getTp() != 0) {
                tvStopProfit.setText(BaseUtils.getDigitsData(traderOrder.getTp(), digits));
                double tt = getMyProfit(traderOrder.getTp());
                tvProfit.setText("预期盈亏：" + BaseUtils.dealSymbol(tt));
            }
            if (traderOrder.getSl() != 0) {
                tvStopLoss.setText(BaseUtils.getDigitsData(traderOrder.getSl(), digits));
                double pp = getMyProfit(traderOrder.getSl());
                tvLoss.setText("预期盈亏：" + BaseUtils.dealSymbol(pp));
            }
            firstIn = 1;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        presenter.stopRealTimerQuote();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.stopRealTimerQuote();
        CloseAllActivity.getScreenManager().popActivity(this);

    }

    /**
     * 修改止盈／止损
     *
     * @param ticket
     * @param userId
     * @param tp
     * @param sl
     */
    private void traderUpdata(String ticket, int userId, final double tp, final double sl) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("userId", userId + "");
        map.put("ticket", ticket + "");
        map.put("tp", tp + "");
        map.put("sl", sl + "");
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.CHANGE_STOPLOSS_OR_PROFIT_ACTIVITY_TRADER_UPDATA, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast(R.string.net_error);
                dismissShortDialog();
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = "";
                    String errMsg = "";
                    if (!jsonObject.get("err_code").isJsonNull())
                        errCode = jsonObject.get("err_code").getAsString();
                    if (!jsonObject.get("err_msg").isJsonNull())
                        errMsg = jsonObject.get("err_msg").getAsString();
                    if (errCode.equals("0")) {
                        showToast("修改成功");
                        EventBus.getDefault().post(new EventDatas(EventContents.CHANGE_STOPLOSS_OR_PROFIT, new double[]{tp, sl}));
                        finish();
                    } else
                        showToast(errMsg);
                }
                dismissShortDialog();
            }
        });
    }

    /**
     * who: 0：价格 1：手数 2：止损 3：止盈
     */
    class EditTextListener implements TextWatcher {
        int who;

        public EditTextListener(int who) {
            this.who = who;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //限制最大值和最小值
            String text = s.toString();
            int dotIndex = text.indexOf(".");
            int textLength = text.length();

            if (dotIndex == 0) {
                return;
            }
            if (textLength - 1 == dotIndex) {
                text = text + "00";
            }
            switch (who) {
                case 0:
                    if (textLength - dotIndex > digits + 1 && dotIndex != -1) {
                        text = text.substring(0, dotIndex + digits + 1);
                    }
                    double stopLosPre = Double.parseDouble(text);
                    if (cmd == 0) {
                        if (stopLosPre <= mStopLoss) {
                            sl = stopLosPre;
                            stopLossTotal = Arith.sub(stopLosPre, mStopLoss);
                            double profit;
                            profit = getMyProfit(sl);

                            if (profit == -1) return;
                            tvLoss.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
                        } else {
                            sl = 0;
                            tvLoss.setText("不在范围内");
                        }

                    } else {
                        if (stopLosPre >= mStopLoss) {
                            sl = stopLosPre;
                            stopLossTotal = Arith.sub(stopLosPre, mStopLoss);
                            double profit;
                            profit = getMyProfit(sl);

                            if (profit == -1) return;
                            tvLoss.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
                        } else {
                            sl = 0;
                            tvLoss.setText("不在范围内");
                        }
                    }
                    break;
                case 1:
                    if (textLength - dotIndex > digits + 1 && dotIndex != -1) {
                        text = text.substring(0, dotIndex + digits + 1);
                    }
                    double stopProPre = Double.parseDouble(text);
                    if (cmd == 0) {
                        if (stopProPre >= mStopProfit) {
                            tp = stopProPre;
                            stopProfitTotal = Arith.sub(stopProPre, mStopProfit);
                            double profit;
                            profit = getMyProfit(tp);
                            if (profit == -1) return;
                            tvProfit.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
                        } else {
                            tp = 0;
                            tvProfit.setText("不在范围内");
                        }

                    } else {
                        if (stopProPre <= mStopProfit) {
                            tp = stopProPre;
                            stopProfitTotal = Arith.sub(stopProPre, mStopProfit);
                            double profit;
                            profit = getMyProfit(tp);
                            if (profit == -1) return;
                            tvProfit.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
                        } else {
                            tp = 0;
                            tvProfit.setText("不在范围内");
                        }
                    }
                    break;
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

}
